package cool.mtc.web.annotation.serializer.amount;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.text.DecimalFormat;

/**
 * @author yz
 */
@Slf4j
public class AmountSerializer extends StdSerializer<Long> implements ContextualSerializer {
    private int decimalPlaces;
    private DecimalFormat decimalFormat;

    public AmountSerializer() {
        super(Long.class);
    }

    public AmountSerializer(int decimalPlaces) {
        super(Long.class);
        this.decimalPlaces = decimalPlaces;
        this.decimalFormat = new DecimalFormat("#0." + this.repeat("0", decimalPlaces));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) {
        Amount annotation = property.getAnnotation(Amount.class);
        return new AmountSerializer(annotation.decimalPlaces());
    }

    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (null == value || this.decimalPlaces <= 0) {
            return;
        }
        double decimal = (double) value / Math.pow(10, this.decimalPlaces);
        gen.writeObject(this.decimalFormat.format(decimal));
    }

    public String repeat(String repeatStr, int repeatTimes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < repeatTimes; i++) {
            sb.append(repeatStr);
        }
        return sb.toString();
    }
}
